package com.bds.btcdc.adapter.bitstamp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.service.IAdapterService;
import com.bds.btcdc.http.HttpUtil;
import com.bds.btcdc.model.CoinPairExchanges;
import com.bds.btcdc.model.MarketData;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DongChenchen on 2018/4/9 0009 交易所：https://www.bitstamp.net
 */
@Service
public class BitstampServiceImpl implements IAdapterService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static final String EXCHANGE = "BITSTAMP";
    public static final String TICKER = "ticker/";
    private static final DecimalFormat df = new DecimalFormat("#.00");


    /**
     * 仅获取btc行情 btcusd, btceur, eurusd, xrpusd, xrpeur, xrpbtc, ltcusd, ltceur,
     * ltcbtc, ethusd, etheur, ethbtc, bchusd, bcheur, bchbtc
     *
     * @return Response (JSON) last Last BTC price. high Last 24 hours price
     * high. low Last 24 hours price low. vwap Last 24 hours volume
     * weighted average price. volume Last 24 hours volume. bid Highest
     * buy order. ask Lowest sell order. timestamp Unix timestamp date
     * and time. open First price of the day.
     */
    @Override
    public Result getMarketInfo(List<CoinPairExchanges> pairs) {
        Result ret = new Result();
        List<MarketData> ms = new ArrayList<MarketData>();
        String errorMsg="";
        for(CoinPairExchanges pair:pairs) {
            String btsPair = pair.getEn_pair_code().replace("_", "");
            String url = Const.BITSTAMP.URL + TICKER + btsPair;
            try {
                HttpUtil httpUtil = HttpUtil.getInstance();
                String jsonStr = httpUtil.get(url, null, false);
//                logger.info("从bitstamp获取行情: " + jsonStr);
                if (StringUtils.isEmpty(jsonStr)) {
                    ret.setCode(Const.FAIL_400);
                    ret.setMsg("没有此交易所数据bitstamp");
                    return ret;
                }
                JSONObject obj = JSONObject.parseObject(jsonStr);
                String date = obj.getString("timestamp");
                MarketData data = new MarketData();
                data.setTimestamp(Long.parseLong(date));
                data.setExchange(EXCHANGE);
                data.setLast(obj.getString("last"));
                data.setBuy(obj.getString("bid"));
                data.setSell(obj.getString("ask"));
                data.setHigh(obj.getString("high"));
                data.setLow(obj.getString("low"));
                data.setVol(df.format(obj.getBigDecimal("volume")));
                data.setPair(pair.getEn_pair_code());
                ms.add(data);
            } catch (Exception e) {
                logger.info("请求异常：" + url);
                errorMsg=errorMsg+"请求异常：" + url + " 异常信息：" + e.getMessage()+"\n";
            }
        }
        if(ms.size()>0) {
            ret.setCode(Const.SUC);
            ret.setData(ms);
            return ret;
        }else{
            ret.setCode(Const.FAIL_500);
            ret.setMsg(errorMsg);
            return ret;
        }
    }

    /**
     * 获取所有货币 行情
     *
     * @return
     */
    public Result getMarketInfoOfAll() {
        Result ret = new Result();
//        String[] currency_pairs = Const.CURRENCY_PAIRS;
        String[] currency_pairs =new String[]{};//TODO
        JSONObject jsonObject = new JSONObject();
        for (String currency_pair : currency_pairs) {
            String url = Const.BITSTAMP.URL + TICKER + currency_pair;
//            logger.info("请求：" + url);
            try {
                HttpUtil httpUtil = HttpUtil.getInstance();
                String jsonStr = httpUtil.get(url, null, false);
                if (!StringUtils.isEmpty(jsonStr)) {
                    jsonObject.put(currency_pair, jsonStr);
                }
            } catch (Exception e) {
                logger.info("请求异常：" + url);
                e.printStackTrace();
                continue;
            }
        }
        if (jsonObject.keySet().size() <= 0) {
            ret.setCode(Const.FAIL_500);
            ret.setMsg("没有此交易所数据bitstamp");
            return ret;
        }
        ret.setCode(Const.SUC);
        ret.setData(jsonObject.toJSONString());
        return ret;
    }


}
